package com.cindata

import com.cindata.dic.BuildingTypeDict
import com.cindata.dictionary.OrganizationNatureDict
import grails.transaction.Transactional
import org.springframework.security.access.annotation.Secured

import java.text.SimpleDateFormat

import static org.springframework.http.HttpStatus.*
import grails.converters.JSON

@Secured(['isAuthenticated()'])
@Transactional
class DeveloperController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def dataSource
    def springSecurityService
    def apiService
    def developerApiService

//    def index(Integer max) {
//        params.max = Math.min(max ?: 10, 100)
//        respond Developer.list(params), model:[developerCount: Developer.count()]
//    }

    def show(Developer developer) {
        respond developer
    }

    def create() {
        respond new Developer(params)
    }

    @Transactional
    def save(Developer developer) {
        if (developer == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (developer.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond developer.errors, view:'create'
            return
        }

        developer.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.created.message', args: [message(code: 'developer.label', default: 'Developer'), developer.id])
                redirect developer
            }
            '*' { respond developer, [status: CREATED] }
        }
    }

    def edit(Developer developer) {
        respond developer
    }

    @Transactional
    def update(Developer developer) {
        if (developer == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (developer.hasErrors()) {
            transactionStatus.setRollbackOnly()
            respond developer.errors, view:'edit'
            return
        }

        developer.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'developer.label', default: 'Developer'), developer.id])
                redirect developer
            }
            '*'{ respond developer, [status: OK] }
        }
    }

    @Transactional
    def delete(Developer developer) {

        if (developer == null) {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        developer.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'developer.label', default: 'Developer'), developer.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'developer.label', default: 'Developer'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }


    def search()
    {

    }


    def searchCompany()
    {
        def keywords = params['keywords']
        println "keywords:" + keywords
        def result = apiService.searchCompany(keywords, 5)
        println result
        def str = []
        def companyIds = []
        int flag = 0
        result.data.each {
            str[flag] = it.companyName
            companyIds[flag] = it.companyId
            flag++
        }

        render([s: str, id: companyIds] as JSON)
    }

//    def detail()
//    {
//        def companyId = params['companyId']
//        def companyName = params['companyName']
//        def companyInfo = developerApiService.getCompanyInfo(companyName)
//        def projectList = apiService.getCompanyProject(companyId, 1, 5)
//        println "companyInfo--" + companyInfo
//        println "projectList--" + projectList
//        def info
//        companyInfo?.items.each {
//            if (it?.type.equals("基本"))
//            {
//                info = it?.items
//            }
//        }
//        println "start"
//        def inf = new HashMap<String,String>()
//        inf.put("companyName",companyName)
//        info.each{
//            if(it.name =="成立日期" ){
//                inf.put("foundDate",it?.value)
//            }
//            if(it.name =="登记住所" ){
//                inf.put("companyAddress",it?.value)
//            }
//            if(it.name =="企业类型" ){
//                inf.put("companyType",it?.value)
//            }
//            if(it.name =="经营（驻在）期限自" ){
//                inf.put("businessperiodStart",it?.value)
//            }
//            if(it.name =="经营（驻在）期限至" ){
//                inf.put("businessperiodEnd",it?.value)
//            }
//            if(it.name =="登记机关" ){
//                inf.put("registrationAuthorit",it?.value)
//            }
//            if(it.name =="注册资金" ){
//                inf.put("regamt",it?.value)
//            }
//            if(it.name =="所属行业" ){
//                inf.put("industryType",it?.value)
//            }
//            if(it.name =="法人名称" ){
//                inf.put("legalPerson",it?.value)
//            }
//            if(it.name =="经营范围" ){
//                inf.put("businessScope",it?.value)
//            }
//            if(it.name =="企业状态" ){
//                inf.put("businessState",it?.value)
//            }
//            if(it.name =="核准日期" ){
//                inf.put("lssueDate",it?.value)
//            }
//            if(it.name =="注册资金币种" ){
//                inf.put("billType",it?.value)
//            }
//        }
//        // println companyInfo
//        // println "info:" + info
//        println projectList
//        def size = 0
//        projectList?.data.each {
//            size++
//        }
//        respond companyInfo, model: [companyInfo: inf, projectList: projectList?.data, size: size],view :"detail"
//    }

    def detail()
    {
        def companyId = params['companyId']
        def companyName = params['companyName']
        def companyInfo = developerApiService.getOrginInfo(companyName)
        def projectList = apiService.getCompanyProject(companyId, 1, 5)
        println "companyInfo--" + companyInfo
        println "projectList--" + projectList
        def baseInfo
        if(companyInfo?.企业工商精确?.gsname  && companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben ){
            baseInfo = companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben[0]
        }
        println "baseInfo-->>"+baseInfo

        println "start"
        def inf = new HashMap<String,String>()
        inf.put("companyName",companyName)

        //处理负面信息
        List<Map<String,String>> list = new ArrayList<HashMap<String,String>>()

        //执行金额
        def zhixingMoney = 0
        //欠税金额
        def qianshuiMoney = 0
        //失信被执行金额
        def shixinMoney = 0
        //欠款欠税金额
        def qiankuanMoney = 0
        //被裁判金额
        def caipanMoney = 0

        //民事审批被告记录
        def shenpanCount = 0
        //那种是否正常
        boolean  isNormal = true
        //被限制出境人数
        def xianchuCount  = 0
        //被限制高消费人数
        def xiangaoCount = 0
        //行政违法记录
        def weifaCount = 0
        //犯罪嫌疑人
        def fanzuiCount = 0


        //执行公开信息
        companyInfo?.企业单笔精确?.fxcontent?.zhixing?.each{
            zhixingMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","执行公开信息")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //失信被执行信息
        companyInfo?.企业单笔精确?.fxcontent?.shixin?.each{
            shixinMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","失信被执行信息")
            map.put("name",it?.name)
            map.put("money",it?.wlmoney)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制高消费记录
        companyInfo?.企业单笔精确?.fxcontent?.xiangao?.each{
            xiangaoCount++
            Map map = new HashMap()
            map.put("type","限制高消费记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制出入境记录
        companyInfo?.企业单笔精确?.fxcontent?.xianchu?.each{
            xianchuCount++
            Map map = new HashMap()
            map.put("type","限制出入境记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事裁判记录
        companyInfo?.企业单笔精确?.fxcontent?.caipan?.each{
            caipanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","民事裁判记录")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事审判记录
        companyInfo?.企业单笔精确?.fxcontent?.shenpan?.each{
            shenpanCount++
            Map map = new HashMap()
            map.put("type","民事审判记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //罪犯及嫌疑人记录
        companyInfo?.企业单笔精确?.fxcontent?.zuifan?.each{
            fanzuiCount++
            Map map = new HashMap()
            map.put("type","罪犯及嫌疑人记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //行政违法记录
        companyInfo?.企业单笔精确?.fxcontent?.weifa?.each{
            weifaCount++
            Map map = new HashMap()
            map.put("type","行政违法记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠税名单
        companyInfo?.企业单笔精确?.fxcontent?.qianshui?.each{
            qianshuiMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠税名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.taxperiod)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //纳税非正常户
        companyInfo?.企业单笔精确?.fxcontent?.feizheng?.each{
            isNormal = false
            Map map = new HashMap()
            map.put("type","纳税非正常户")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠款欠费名单
        companyInfo?.企业单笔精确?.fxcontent?.qiankuan?.each{
            qiankuanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠款欠费名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        list.each {
        it?.content = it.content.replace("<p>","").replace("</p>","")
        }
        println projectList
        def size = 0
        projectList?.data.each {
            size++
        }
        respond companyInfo, model: [companyName:companyName,companyInfo: baseInfo  ,fumianList:list, projectList: projectList?.data, size: size,
                                     zhixingMoney:(zhixingMoney/10000).toInteger(),qianshuiMoney:(qianshuiMoney/10000).toInteger(),shixinMoney:(shixinMoney/10000).toInteger(),qiankuanMoney:(qiankuanMoney/10000).toInteger(),caipanMoney:(caipanMoney/10000).toInteger(),shenpanCount:shenpanCount,
                                     isNormal:isNormal,xianchuCount:xianchuCount,xiangaoCount:xiangaoCount,weifaCount:weifaCount,fanzuiCount:fanzuiCount],view :"detail"
    }

    /**
     * ajax获取开发商项目*/
    def ajaxproject()
    {

    }

    def map()
    {
        respond(view: "map")
    }

    /**
     * 开发商地图数据*/
    def developerMapData()
    {
        def mapDataStatus = ""
        def result = new HashMap()
        def mapDataList = new ArrayList()
        def conditionQueryParam = new HashMap()
        def city = params["city"]
        def province = params["province"]
        //城市
        def level = params["level"]
        //片区
        try
        {
            def user = User.findById(springSecurityService.principal.id)
            //登录用户
            def userAccount = user.account
            //用户所属机构
            if (!userAccount)
            {
                result["mapDataList"] = mapDataList
                render([result: result] as JSON)
                return
            }
            if (city == "-1" && level == "1")
            {
                //全国下的省开发商
                def aroundAccountSql = " select new map( a.name as name ,a.longitude as lng ,a.latitude as lat ,a.zoneNumber as zoneNumber ,count(distinct e.developer.id) as count ) from Estate e join e.province a where e.isEstate = true "
                aroundAccountSql = aroundAccountConditionSql(aroundAccountSql, params, conditionQueryParam, user, 2)
                aroundAccountSql += " group by a.name ,a.zoneNumber ,a.longitude,a.latitude "
                mapDataList = Estate.executeQuery(aroundAccountSql, conditionQueryParam)
            }
            else if (province && province != "-1" && level == "2")
            {
                //省下的市开发商
                def aroundAccountSql = " select new map( a.name as name ,a.longitude as lng ,a.latitude as lat ,a.zoneNumber as zoneNumber ,count(distinct e.developer.id) as count ) from Estate e join e.city a where e.isEstate = true "
                aroundAccountSql = aroundAccountConditionSql(aroundAccountSql, params, conditionQueryParam, user, 2)
                aroundAccountSql += " group by a.name ,a.zoneNumber ,a.longitude,a.latitude "
                mapDataList = Estate.executeQuery(aroundAccountSql, conditionQueryParam)
            }
            else if (city && city != '-1' && level == "3")
            {
                //市下的行政区开发商
                def aroundAccountSql = " select new map ( a.name as name , a.zoneNumber as zoneNumber,a.longitude as lng ,a.latitude as lat ,count(distinct e.developer.id) as count) from Estate e inner join e.district a where e.isEstate = true "
                aroundAccountSql = aroundAccountConditionSql(aroundAccountSql, params, conditionQueryParam, user, 2)
                aroundAccountSql += " group by a.name ,a.zoneNumber,a.longitude,a.latitude "
                mapDataList = Estate.executeQuery(aroundAccountSql, conditionQueryParam)
            }
            mapDataStatus = "true"
            result["mapDataStatus"] = mapDataStatus
            result["mapDataList"] = mapDataList
        }
        catch (Exception e)
        {
            mapDataStatus = "false"
            result["mapDataStatus"] = mapDataStatus
            result["mapDataList"] = mapDataList
            e.printStackTrace()
        }
        render([result: result] as JSON)
    }

    /**
     * 开发商小区*/
    def developerCommunityData()
    {
        def mapDataStatus = ""
        def result = new HashMap()
        def communityList = new ArrayList()
        def conditionQueryParam = new HashMap()
        def buildQueryParam = new HashMap()
        def estateQueryParam = new HashMap()
        try
        {
            def user = User.findById(springSecurityService.principal.id)
            //登录用户
            def userAccount = user.account
            //用户所属机构
            if (!userAccount)
            {
                result["mapDataList"] = mapDataList
                render([result: result] as JSON)
                return
            }
            def communitySql = " select new map ( e.communityId as communityId , communityName as communityName, count(e.id) as count ,avg(e.x) as lng ,avg(e.y) as lat ) from Estate e where 1=1 "
            def buildSql = " select new map(e.x as  lng,e.y as lat,count(case when isEstate = true then 1 else null end) as estate, count(case when isEstate = false then 1 else null end) as noEstate ) from Estate e where 1=1 "
            def estateSql = "select new map(e.id as id ,e.externalId as externalId ,e.sourceAddress as sourceAddress ,e.x as lng, e.y as lat,e.isEstate as isEstate ) " + "from Estate e where 1=1 "
            communitySql = aroundAccountConditionSql(communitySql, params, conditionQueryParam, user, 1)
            buildSql = aroundAccountConditionSql(buildSql, params, buildQueryParam, user, 1)
            estateSql = aroundAccountConditionSql(estateSql, params, estateQueryParam, user, 1)
            communitySql += " group by e.communityId ,e.communityName "
            //查询网点小区信息
            communityList = Estate.executeQuery(communitySql, conditionQueryParam)
            communityList.each {
                it.put("buildList", new ArrayList<>())
            }
            for (
                int i = 0;
                    i < communityList.size();
                    i++)
            {
                def bstr = buildSql
                bstr += " and e.communityId = :communityId "
                buildQueryParam['communityId'] = communityList[i].communityId
                bstr += " group by e.x ,e.y "
                //查询小区楼栋的x/y
                def mapDataList = Estate.executeQuery(bstr, buildQueryParam)
                def blist = (List) communityList[i].get("buildList")
                blist.add(mapDataList)
                communityList[i].put("buildList", blist)
                mapDataList.each {
                    it.put("estateList", new ArrayList<>())
                }
                //查询坐标相同押品信息
                for (
                    int j = 0;
                        j < mapDataList.size();
                        j++)
                {
                    def str = estateSql
                    def x = mapDataList[j].lng
                    def y = mapDataList[j].lat
                    str += " and e.x = :x and e.y = :y "
                    estateQueryParam['x'] = x
                    estateQueryParam['y'] = y
                    def elist = Estate.executeQuery(str, estateQueryParam)
                    def list = (List) mapDataList[j].get("estateList")
                    list.add(elist)
                    mapDataList[j].put("estateList", list)
                }
            }
            mapDataStatus = "true"
            result["mapDataStatus"] = mapDataStatus
            result["mapDataList"] = communityList
        }
        catch (Exception e)
        {
            mapDataStatus = "false"
            result["mapDataStatus"] = mapDataStatus
            result["mapDataList"] = communityList
            e.printStackTrace()
        }
        render([result: result] as JSON)
    }

    /**
     * 片区下开发商数据*/
    def developerData()
    {
        def mapDataStatus = ""
        def result = new HashMap()
        def mapDataList = new ArrayList()
        def conditionQueryParam = new HashMap()
        try
        {
            def user = User.findById(springSecurityService.principal.id)
            //登录用户
            def userAccount = user.account
            //用户所属机构
            if (!userAccount)
            {
                result["mapDataList"] = mapDataList
                render([result: result] as JSON)
                return
            }
            def accountSql = " select new map( a.x as lng ,a.y as lat ,a.name as name ,a.id as id ,count(distinct e.communityId) as count ) from Estate e join e.developer a where 1=1 "
            accountSql = aroundAccountConditionSql(accountSql, params, conditionQueryParam, user, 1)
            accountSql += " group by a.name ,a.id  ,a.x,a.y  "
            mapDataList = Estate.executeQuery(accountSql, conditionQueryParam)
            mapDataStatus = "true"
            result["mapDataStatus"] = mapDataStatus
            result["mapDataList"] = mapDataList
        }
        catch (Exception e)
        {
            mapDataStatus = "false"
            result["mapDataStatus"] = mapDataStatus
            result["mapDataList"] = mapDataList
            e.printStackTrace()
        }
        render([result: result] as JSON)
    }

    /**
     * 行政区下片区地图数据
     * @return
     */
    def developerPrecinctData()
    {
        def mapDataStatus = ""
        def result = new HashMap()
        def mapDataList = new ArrayList()
        def conditionQueryParam = new HashMap()
        try
        {
            def user = User.findById(springSecurityService.principal.id)
            //登录用户
            def userAccount = user.account
            //用户所属机构
            if (!userAccount)
            {
                result["mapDataList"] = mapDataList
                render([result: result] as JSON)
                return
            }
            def communitySql = " select new map(a.name as name , a.id as precinctId,a.longitude as lng ,a.latitude as lat ,a.coordinates as coordinates ,count(distinct e.developer.id) as count ) from Estate e join e.precinct a where e.isEstate = true "
            communitySql = aroundAccountConditionSql(communitySql, params, conditionQueryParam, user, 1)
            communitySql += " group by e.name ,e.id ,a.longitude ,a.latitude ,a.coordinates "
            mapDataList = Estate.executeQuery(communitySql, conditionQueryParam)
            mapDataStatus = "true"
            result["mapDataStatus"] = mapDataStatus
            result["mapDataList"] = mapDataList
        }
        catch (Exception e)
        {
            mapDataStatus = "false"
            result["mapDataStatus"] = mapDataStatus
            result["mapDataList"] = mapDataList
            e.printStackTrace()
        }
        render([result: result] as JSON)

    }

    /**
     * 开发商地图条件*/
    def aroundAccountConditionSql(estateSql, params, conditionQueryParam, user, type)
    {
        def province = params["province"]
        //省
        def city = params["city"]
        //城市
        def district = params["district"]
        //行政区
        def precinct = params["precinct"]
        //片区
        def developerName = params["developerName"]
        //开发商名称
        def developerId = params["developerId"]
        //开发商名称Id
        estateSql = Estate.FilterAccount(estateSql, conditionQueryParam, user)
        if (city && city != '-1')
        {
            if (type == 1)
            {
                estateSql += " and e.city.zoneNumber = :city "
            }
            else if (type == 2)
            {
                estateSql += " and a.parentArea.zoneNumber = :city "
            }
            conditionQueryParam["city"] = city
        }
        if (district && district != '-1')
        {
            estateSql += " and e.district.zoneNumber = :district "
            conditionQueryParam["district"] = district
        }
        if (precinct && precinct != '-1')
        {
            estateSql += " and e.precinct.id = :precinct "
            conditionQueryParam["precinct"] = precinct
        }
        if (province && province != '-1')
        {
            estateSql += " and e.province.zoneNumber = :province "
            conditionQueryParam["province"] = province
        }
        if (developerName && developerName != '')
        {
            estateSql += " and e.developer.name like :developerName "
            conditionQueryParam["developerName"] = "%" + developerName + "%"
        }
        if (developerId)
        {
            estateSql += " and e.developer.id = :developerId "
            conditionQueryParam["developerId"] = Long.parseLong(developerId)
        }
        return estateSql
    }

    def init ()
    {
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
//        Developer d = new Developer()
//        d.name = "福建兰庭房产代理有限公司"
//        d.address = "福州市鼓楼区五一北路171号新都会花园广场10层A单元"
//        d.unitNature = OrganizationNatureDict.StateOwnedEnterprise()
//        d.unifiedSocialCreditCode = "无"
//        d.status = "设立登记"
//        d.operatingState = "经营中"
//        d.registrationNumber = "10001"
//        d.registeredCapital = 1000000
//        d.creditRating = "AAAA"
//        d.qualificationGrade = "建筑商"
//        d.legalRepresentative = "陈梅"
//        d.legalRepresentativeCredit="AAA"
//        d.caseOfComplaintAmount = 10
//        d.assetRatio = 0.5
//        d.entryStatus = "已入围"
//        d.scopeOfBusiness = "房产营销策划、房产居间服务、房产代理、房产经济信息咨询。（以上经营范围涉及许可经营项目的，应在取得有关部门的许可后方可经营）"
//        d.type = "有限责任公司（自然人投资或控股的法人独资）"
//        d.industry = "房地产业"
//        d.establishDate = sdf.parse("2006-06-28")
//        d.operatingPeriod = 20
//        d.operatingYears = "2006-06-28 至 2026-06-27"
//        d.approvalDate = sdf.parse("2015-12-09")
//        d.registerOrg = "福州市工商行政管理局"
//        d.save(flush:true)

//        Developer d = Developer.findById(6026103)
//        DeveloperProject dp = new DeveloperProject()
//        dp.name="项目1"
//        dp.city = City.findByName("广州市")
//        dp.address = "广东省广州市天河区"
//        dp.entryStatus="已入围"
//        dp.buildingstructure = "钢筋混合"
//        dp.preSalePermitNumber = "112345544"
//        dp.completionDate = new Date()
//        dp.deliveryDate = new Date()
//        dp.developer = d
//        dp.save(flush:true)
//        DeveloperProject dp2 = new DeveloperProject()
//        dp2.name="项目2"
//        dp2.city = City.findByName("广州市")
//        dp2.address = "广东省广州市天河区"
//        dp2.entryStatus="已入围"
//        dp2.buildingstructure = "钢筋混合"
//        dp2.preSalePermitNumber = "13212212121222"
//        dp2.completionDate = new Date()
//        dp2.deliveryDate = new Date()
//        dp2.developer = d
//        dp2.save(flush:true)

        def dp = DeveloperProject.findById(6026108)
        def dpb  = new DeveloperProjectBuilding()
        dpb.name = "碧桂园新城"
        dpb.address = "广东省广州市天河区大西厂路35号"
        dpb.certificateNumber = "1212121212"
        dpb.coveringArea = 5632
        dpb.totalBuildingArea = 5632
        dpb.project = dp
        dpb.save(flush:true)
        def dpb2  = new DeveloperProjectBuilding()
        dpb2.name = "绿地花苑"
        dpb2.address = "广东省广州市天河区大西厂路35号"
        dpb2.certificateNumber = "1212121212"
        dpb2.coveringArea = 5632
        dpb2.totalBuildingArea = 5632
        dpb2.project = dp
        dpb2.save(flush:true)

    }
     def index()
     {
         def city = params["city"]
         //城市
         def district = params["district"]
         //行政区
         def name = params["name"]
         def sql = "from Developer d where 1 = 1  "
         if(city && city!= '-1'){
             sql += " and d.city = '"+city+"'"
         }
         if(district && district!= '-1'){
             sql += " and d.district = '"+district+"'"
         }
         if(name && name!= '-1'){
             sql += " and d.name = '" + name + "'"
         }

         def list = Developer.executeQuery(sql)
         println "list size:"+list.size()
         respond list, model: [list:list],view :"index"

     }

    def detailn()
    {
        def companyId = params['companyId']
        def companyName = params['companyName']
        def developer = Developer.findByCompanyId(companyId)
        if(developer){
            println "存在"
        }else{
            println "不存在"
            redirect action: "detail",params:[companyId:companyId,companyName:companyName]
            return
        }
        def companyInfo = developerApiService.getOrginInfo(developer?.name)
        // println "companyInfo--" + companyInfo
        def baseInfo
        if(companyInfo?.企业工商精确?.gsname  && companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben ){
            baseInfo = companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben[0]
        }
        // println "baseInfo-->>"+baseInfo

        println "start"
        def inf = new HashMap<String,String>()
        //处理负面信息
        List<Map<String,String>> list = new ArrayList<HashMap<String,String>>()

        //执行金额
        def zhixingMoney = 0
        //欠税金额
        def qianshuiMoney = 0
        //失信被执行金额
        def shixinMoney = 0
        //欠款欠税金额
        def qiankuanMoney = 0
        //被裁判金额
        def caipanMoney = 0

        //民事审批被告记录
        def shenpanCount = 0
        //那种是否正常
        boolean  isNormal = true
        //被限制出境人数
        def xianchuCount  = 0
        //被限制高消费人数
        def xiangaoCount = 0
        //行政违法记录
        def weifaCount = 0
        //犯罪嫌疑人
        def fanzuiCount = 0


        //执行公开信息
        companyInfo?.企业单笔精确?.fxcontent?.zhixing?.each{
            zhixingMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","执行公开信息")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //失信被执行信息
        companyInfo?.企业单笔精确?.fxcontent?.shixin?.each{
            shixinMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","失信被执行信息")
            map.put("name",it?.name)
            map.put("money",it?.wlmoney)
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制高消费记录
        companyInfo?.企业单笔精确?.fxcontent?.xiangao?.each{
            xiangaoCount++
            Map map = new HashMap()
            map.put("type","限制高消费记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //限制出入境记录
        companyInfo?.企业单笔精确?.fxcontent?.xianchu?.each{
            xianchuCount++
            Map map = new HashMap()
            map.put("type","限制出入境记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state",it?.state)
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事裁判记录
        companyInfo?.企业单笔精确?.fxcontent?.caipan?.each{
            caipanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","民事裁判记录")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //民事审判记录
        companyInfo?.企业单笔精确?.fxcontent?.shenpan?.each{
            shenpanCount++
            Map map = new HashMap()
            map.put("type","民事审判记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //罪犯及嫌疑人记录
        companyInfo?.企业单笔精确?.fxcontent?.zuifan?.each{
            fanzuiCount++
            Map map = new HashMap()
            map.put("type","罪犯及嫌疑人记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //行政违法记录
        companyInfo?.企业单笔精确?.fxcontent?.weifa?.each{
            weifaCount++
            Map map = new HashMap()
            map.put("type","行政违法记录")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.content)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠税名单
        companyInfo?.企业单笔精确?.fxcontent?.qianshui?.each{
            qianshuiMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠税名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.taxperiod)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //纳税非正常户
        companyInfo?.企业单笔精确?.fxcontent?.feizheng?.each{
            isNormal = false
            Map map = new HashMap()
            map.put("type","纳税非正常户")
            map.put("name",it?.name)
            map.put("money","--")
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        //欠款欠费名单
        companyInfo?.企业单笔精确?.fxcontent?.qiankuan?.each{
            qiankuanMoney += it?.money ? Double.parseDouble(it?.money):0
            Map map = new HashMap()
            map.put("type","欠款欠费名单")
            map.put("name",it?.name)
            map.put("money",it?.money)
            map.put("content",it?.title)
            map.put("state","--")
            map.put("sslong",it?.sslong)
            list.add(map)
        }

        list.each {
            it?.content = it.content.replace("<p>","").replace("</p>","")
        }

        respond companyInfo, model: [companyInfo: developer  ,fumianList:list,
                                     zhixingMoney:(zhixingMoney/10000).toInteger(),qianshuiMoney:(qianshuiMoney/10000).toInteger(),shixinMoney:(shixinMoney/10000).toInteger(),qiankuanMoney:(qiankuanMoney/10000).toInteger(),caipanMoney:(caipanMoney/10000).toInteger(),shenpanCount:shenpanCount,
                                     isNormal:isNormal,xianchuCount:xianchuCount,xiangaoCount:xiangaoCount,weifaCount:weifaCount,fanzuiCount:fanzuiCount],view :"detailn"
    }

    def projectDetail(DeveloperProject developerProject)
    {
        respond developerProject

    }

    def buildingDetail(DeveloperProjectBuilding developerProjectBuilding)
    {
        respond developerProjectBuilding
    }

    def detail1()
    {
       def companyId = params['companyId']
       def companyName = params['companyName']
        println companyId
        println companyName
        respond true, model:[companyId:companyId,companyName:companyName]
    }

    /**
     * 开发商入围
     */
    def beSelected()
    {
        def companyId = params['companyId']
        def companyName = params['companyName']
        //根据开发商id去调取接口查询开发商信息
        //保存开发商信息和项目信息
        //跳转到详情页
        def companyInfo = developerApiService.getOrginInfo(companyName)
        //def projectList = apiService.getCompanyProject(companyId, 1, 999)
        println "companyInfo--" + companyInfo
       // println "projectList--" + projectList
        def baseInfo
        if(companyInfo?.企业工商精确?.gsname  && companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben ){
            baseInfo = companyInfo?.企业工商精确?.gsname[0]?.gsurl?.gscontent?.jiben[0]
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd")
        def developer = new Developer()
        developer.companyId = companyId
        developer.name = companyName
        developer.entryStatus = "已入围"
        developer.unifiedSocialCreditCode = baseInfo?.creditcode
        developer.legalRepresentative = baseInfo?.name
        developer.status = baseInfo?.entstatus
        developer.registrationNumber = baseInfo?.regno
        developer.registeredCapital = baseInfo?.regcap ? new BigDecimal(baseInfo?.regcap ) : 0
        developer.registeredcur = baseInfo?.regcapcur
        developer.type = baseInfo?.enttype
        developer.industry = baseInfo?.industryphy
        developer.address = baseInfo?.dom
        developer.establishDate = baseInfo?.esdate ? sdf.parse(baseInfo?.esdate) : null
        developer.operatingYears = baseInfo?.opfrom+" 至 "+baseInfo?.opto
        developer.approvalDate = baseInfo?.apprdate ? sdf.parse(baseInfo?.apprdate) : null
        developer.registerOrg = baseInfo?.regorg
        developer.logoutDate = baseInfo?.canceldate ? sdf.parse(baseInfo.canceldate) : null
        developer.revocationDate = baseInfo?.revokedate ? sdf.parse(baseInfo.revokeDate) : null
        developer.scopeOfBusiness = baseInfo?.opscoandform
        developer.save(flush:true)
//        projectList?.data.each {
//            println it
//        }

        redirect action: "index"
    }

    def detail2()
    {

    }
}
